<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use EasyDingTalk\Application;
use App\Models\DingTalkApp;
use App\Models\DingTalkSetting;
use Illuminate\Support\Facades\Request;

class DingTalkServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
        $this->app->singleton('DT', function ($app) {

            $config = DingTalkSetting::first();
            // $ServerApp = DingTalkApp::where("creator_id", $userid)->where("name", $name)->first();
            // $appconfig = $config->toArray();
            // if ($ServerApp) {

            //     $appconfig = array_merge($ServerApp->toArray(), $appconfig);
            // }
            // $ServerApp =

            $defaultAppConfig =  DingTalkApp::with("appUrl")->get()->filter(function ($value, $key) use ($config) {
                $value['app_id'] = $value['id'];
                // $value['creator_id'] = user()->id;
                $value['redirect'] = Request::url();
                $config['app'] = array_merge(isset($config['app']) ? $config['app'] : [], [$value['name'] => $value->toArray()]);
                return $value['default'] == 1;
            })->first();

            $ddApp = new Application(array_merge($config->toArray(), $defaultAppConfig->toArray()));
             //设置缓存驱动
            $ddApp->access_token->setCache($config);
            //设置日志驱动
            $ddApp->logger->set($config);
            return $ddApp;
        });
    }

    public function setRobot()
    {
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
